/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package feuerwehr;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.security.MessageDigest;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author GundlaPe
 */
public class Authenticate extends javax.swing.JDialog {

    /**
     * Creates new form Authenticate
     */
    public Authenticate() {
        initComponents();
        jtfBenutzer.setDocument(new JTextFieldLimit(120));
        jpfKennwort.setDocument(new JTextFieldLimit(120));
        jpfKennwortNeu.setDocument(new JTextFieldLimit(120));
        this.setModalityType(ModalityType.DOCUMENT_MODAL);
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation(new Point((int) (screen.getWidth()/2) - 200, (int) (screen.getHeight()/2) - 100));
        setTitle(Feuerwehr.STR_VERSION + " *** Anmeldung *** ");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jtfBenutzer = new javax.swing.JTextField();
        jpfKennwort = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jbAnmeldung = new javax.swing.JButton();
        jbAendern = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jpfKennwortNeu = new javax.swing.JPasswordField();
        jcbAnzeige = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jtfBenutzer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfBenutzerActionPerformed(evt);
            }
        });

        jpfKennwort.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jpfKennwortActionPerformed(evt);
            }
        });

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel1.setLabelFor(jtfBenutzer);
        jLabel1.setText("Benutzername:");

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel2.setLabelFor(jpfKennwort);
        jLabel2.setText("Kennwort:");

        jbAnmeldung.setText("Anmelden");
        jbAnmeldung.setPreferredSize(new java.awt.Dimension(100, 23));
        jbAnmeldung.setSelected(true);
        jbAnmeldung.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAnmeldungActionPerformed(evt);
            }
        });

        jbAendern.setText("Ändern");
        jbAendern.setPreferredSize(new java.awt.Dimension(100, 23));
        jbAendern.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAendernActionPerformed(evt);
            }
        });

        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("Bitte geben Sie einen gültigen Benutzernamen"); // NOI18N

        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("und ein gültiges oder neues Kennwort ein");

        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel5.setText("Neues Kennwort:");

        jcbAnzeige.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Ändern", "Anzeige", "Alle" }));

        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel6.setLabelFor(jcbAnzeige);
        jLabel6.setText("Anzeige:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jbAnmeldung, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(34, 34, 34)
                                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addContainerGap()
                                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jpfKennwortNeu, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jpfKennwort, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                                .addComponent(jtfBenutzer, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                                .addComponent(jcbAnzeige, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(jbAendern, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jtfBenutzer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpfKennwort, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jpfKennwortNeu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jcbAnzeige, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbAnmeldung, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbAendern, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public String getSelectedValue() {
        return jcbAnzeige.getSelectedItem().toString();
    }
    
    /**
     * JButton für Anmelden, Benutzer / Kennwort wird geprüft und gegen DB getestet, Maximal drei Versuche prüfen.
     * @param evt 
     */
    private void jbAnmeldungActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAnmeldungActionPerformed
        int iPK = -1;
        try {
            PreparedStatement ps = Feuerwehr.getConnection().prepareStatement("select pk, password from t_person where kennung = ?");
            ps.setString(1, jtfBenutzer.getText());
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                iPK = rs.getInt(1);
                password = rs.getString(2);
            }
            rs.close();
            ps.close();
        } catch (SQLException exc) {
            System.err.println("ERROR: " + exc.toString());
        }
        String s = String.valueOf(jpfKennwort.getPassword());
        if (password.equals(MD5(s)) && (s.length() > 0)) {
            Feuerwehr.setBenutzer(Person.getPerson(iPK));
            dispose();
        } else {
            errorCount++;
            JOptionPane.showMessageDialog(this, "Benutzername / Kennwort nicht korrekt!\nNoch " + (3 - errorCount) + " Versuche", Feuerwehr.STR_VERSION, JOptionPane.ERROR_MESSAGE);
            Feuerwehr.setBenutzer(null);
            if (errorCount >= 3) {
                dispose();
            }
        }
    }//GEN-LAST:event_jbAnmeldungActionPerformed

    /**
     * JButton für Aendern
     * @param evt 
     */
    private void jbAendernActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAendernActionPerformed
        int iPK = -1;
        try {
            PreparedStatement ps = Feuerwehr.getConnection().prepareStatement("select pk, password from t_person where kennung = ?");
            ps.setString(1, jtfBenutzer.getText());
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                iPK = rs.getInt(1);
                password = rs.getString(2);
            }
            rs.close();
            ps.close();
        } catch (SQLException exc) {
            System.err.println("ERROR: " + exc.toString());
        }
        String oldPassword = String.valueOf(jpfKennwort.getPassword());
        String newPassword = String.valueOf(jpfKennwortNeu.getPassword());
        if (password.equals(MD5(oldPassword)) && (oldPassword.length() > 0)) {
            if (newPassword.length() == 0) {
                JOptionPane.showMessageDialog(this, "Neues Kennwort darf nicht leer sein!", Feuerwehr.STR_VERSION, JOptionPane.ERROR_MESSAGE);
                return;
            }
            Feuerwehr.setBenutzer(Person.getPerson(iPK));
            try {
                PreparedStatement ps = Feuerwehr.getConnection().prepareStatement("update t_person set password = ? where pk = ?");
                ps.setString(1, MD5(newPassword));
                ps.setInt(2, iPK);
                ps.executeUpdate();
                // Feuerwehr.getConnection().commit();
            } catch (SQLException exc) {
                System.err.println("ERROR: " + exc.toString());
            }
            dispose();
        } else {
            errorCount++;
            JOptionPane.showMessageDialog(this, "Benutzername / Kennwort nicht korrekt!\nNoch " + (3 - errorCount) + " Versuche", Feuerwehr.STR_VERSION, JOptionPane.ERROR_MESSAGE);
            Feuerwehr.setBenutzer(null);
            if (errorCount >= 3) {
                dispose();
            }
        }
    }//GEN-LAST:event_jbAendernActionPerformed

    /**
     * Bei Enter im Benutzerfeld den Anmelden-Button "drücken".
     * @param evt 
     */
    private void jtfBenutzerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfBenutzerActionPerformed
        if (jtfBenutzer.getText().equals(""))
            return;
        jbAnmeldungActionPerformed(evt);
    }//GEN-LAST:event_jtfBenutzerActionPerformed
    
    /**
     * Bei Enter im Kennwortfeld den Anmelden-Button "drücken".
     * @param evt 
     */
    private void jpfKennwortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jpfKennwortActionPerformed
        if (jtfBenutzer.getText().equals(""))
            return;
        jbAnmeldungActionPerformed(evt);
    }//GEN-LAST:event_jpfKennwortActionPerformed

    private String MD5(String md5) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
            }
            // System.err.println("DEBUG[MD5]>> " + sb.toString());
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        }
        return null;
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Authenticate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Authenticate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Authenticate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Authenticate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Authenticate().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JButton jbAendern;
    private javax.swing.JButton jbAnmeldung;
    private javax.swing.JComboBox jcbAnzeige;
    private javax.swing.JPasswordField jpfKennwort;
    private javax.swing.JPasswordField jpfKennwortNeu;
    private javax.swing.JTextField jtfBenutzer;
    // End of variables declaration//GEN-END:variables

    private String benutzer = "";
    private String password = "";
    private int errorCount = 0;
}
